﻿using CinemaMaestro.BusinessLayer.Contracts;
using CinemaMaestro.Common.IocContainer;
using CinemaMaestro.DataLayer.Contracts.Entities;
using CinemaMaestro.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CinemaMaestro.WebApi.Controllers
{
    public class RoomsController : ApiController
    {

        [HttpGet]
        [Route("api/roomsForCinema/{id}")]
        public IHttpActionResult GetAllRoomsForCinema(int id)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();

            var list = businessUoW.Rooms.Read().Where(x => x.Cinema.Id == id).ToList();

            List<RoomViewModel> models = new List<RoomViewModel>();

            foreach (var model in list)
            {
                RoomViewModel room = model;
                models.Add(room);
            }

            return Ok(models);
        }

        [HttpGet]
        public IHttpActionResult GetRoom(int id)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();

            var room = businessUoW.Rooms.Read().FirstOrDefault(x => x.Id == id);
            if (room == null)
            {
                return NotFound();
            }
            RoomViewModel roomVM = room;
            return Ok(roomVM);
        }

        [HttpPut]
        public IHttpActionResult UpdateRoom(RoomViewModel roomVM)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();
            Room room = roomVM;
            businessUoW.Rooms.Update(room);
            return Ok();
        }

        [HttpDelete]
        public IHttpActionResult DeleteRoom(int id)
        {
            var businessUow = Resolver.Get<IBusinessObjectFactory>();
            var hasDependencies = businessUow.Screenings.ScreeningHasRelationWithRoom(id);
            if (hasDependencies)
            {
                return NotFound();
            }
            var deleted = businessUow.Rooms.Delete(id);
            if (deleted)
            {
                return Ok();
            }
            return NotFound();
        }

        [HttpPost]
        public IHttpActionResult CreateRoom(RoomViewModel roomVM)
        {
            var businessUoW = Resolver.Get<IBusinessObjectFactory>();
            Room room = roomVM;
            businessUoW.Rooms.Create(room);
            return Ok();
        }

    }
}
